﻿var colourTimeouts = [];
function CloseColourPicker(notice_id) {
    $(colourTimeouts[notice_id][1]).removeClass("ff-active");
}

$(function() {

    // ###################
    // ##### Generic #####
    // ###################

    // Colour Labels
    $(".ff-labels-color").hover(
        function(event) {
            // Mouse In
            var notice_id = $(this).closest(".ff-message-notice").attr('data-ff-id');
            $(this).addClass("ff-active");
            if (colourTimeouts[notice_id])
                clearTimeout(colourTimeouts[notice_id][0]);
        },
        function(event) {
            // Mouse Out
            var notice_id = $(this).closest(".ff-message-notice").attr('data-ff-id');
            colourTimeouts[notice_id] = [setTimeout("CloseColourPicker(" + notice_id + ")", 400), this];
        }
    );

    $(".ff-labels-color a").click(function() {

        // Get the colour
        var colour = undefined;
        $(this).closest("[class*='ff-label-color-']").attr("class", function(i, c) {
            colour = c.match(/ff-label-color-[a-z]+/g)[0].substr(15);
        });

        // Check the colour was found
        if (colour == undefined)
            return;


        // Get the notice
        var $notice = $(this).closest(".ff-message-notice")

        // Remove/Add the colour from/to the notice
        $notice
            .attr('class', function(i, c) {
                return c.replace(/ {0,1}ff-color-[a-z]+/g, '');
            })
            .addClass('ff-color-' + colour);

        // Remove/Add the active colour from/to the relavent label
        $notice
            .find("[class*='ff-label-color-']")
            .removeClass("ff-selected")
            .filter(".ff-label-color-" + colour)
            .addClass("ff-selected");


        // Send the new colour to the server
        $.ajax({
            url: $notice.attr("data-ff-modify-href"),
            type: 'POST',
            data: "action=colour&notice_id=" + $notice.attr("data-ff-id") + "&colour=" + (colour == "empty" ? "none" : colour),
            error: function() { alert('Error re-colouring task.  Check your internet connection and try refreshing the page.'); }
        });

        return false;
    });


    // Celendar open/close
    $(".ff-calendar-item .ff-calendar-header a").click(function() {
        var day = $(this).closest(".ff-calendar-item");
        if (day.hasClass("selected")) {
            day.removeClass("selected");
        } else {
            day.addClass("selected");
        }

        return false;
    });



    // #####################
    // ##### Timetable #####
    // #####################
    $(".ff-timetable-container .ff-nav-switch a").live("click", function() {
        // xxx mess about with effects
        $li = $(this).closest("li")

        // Re-add link
        $li.siblings("li.selected").each(function() {
            var oldtext = $(this).text();
            $(this).empty().append("<a href='#'>" + oldtext + "</a>").removeClass("selected");
        });

        // Remove link
        var newtext = $(this).text();
        $li.addClass("selected").empty().append(newtext);

        $(".ff-timetable[data-ff-startdate='" + $li.attr("data-ff-startdate") + "']").slideDown(0, null);
        $(".ff-timetable[data-ff-startdate!='" + $li.attr("data-ff-startdate") + "']").slideUp(0, null);

        return false;
    });

    var lastMobileTimetable = isMobile();

    // Turn mobile timetable on/off
    var setMobileTimetable = function() {
        if (isMobile()) {
            $(".ff-timetable-day").hide();
            $(".ff-timetable-day h3").prepend("<a class='ff-timetable-day-prev' href='#'>&lt;&lt; </a>").append("<a class='ff-timetable-day-next' href='#'> &gt;&gt;</a>");
            $(".ff-timetable").each(function() {
                if ($(this).find(".ff-timetable-day.ff-today").show().length < 1)
                    $(this).find(".ff-timetable-day:first").show();
            });
            $(".ff-timetable-day, .ff-timetable-index").css("width", "50%");
        } else {
            $(".ff-timetable-day").show();
            $(".ff-timetable-day-prev, .ff-timetable-day-next").remove();
            $(".ff-timetable").each(function() {
                $cols = $(this).find(".ff-timetable-day, .ff-timetable-index");
                $cols.css("width", (Math.floor(10000 / $cols.length) / 100) + "%");
            });
        }
    }

    // Initial mobile timetable setup
    setMobileTimetable();

    // Recheck mobile timetable if window is resized
    $(window).resize(function() {
        if (lastMobileTimetable != isMobile()) {
            lastMobileTimetable = isMobile();
            setMobileTimetable();
        }
    });


    // LeftRight: swipe
    ffLoadScript(ffBaseURL + 'Templates/lib/jquery/js/jquery.jswipe.js', 'head', function() {
        $(".ff-timetable").swipe({ swipeLeft: function(t) { ttMobileNext(t) }, swipeRight: function(t) { ttMobilePrev(t) } });
    });

    // LeftRight: Buttons
    $(".ff-timetable-day-prev").live("click", function() { ttMobilePrev($(this).closest(".ff-timetable")); return false; });
    $(".ff-timetable-day-next").live("click", function() { ttMobileNext($(this).closest(".ff-timetable")); return false; });


    var ttMobilePrev = function(tt) {
        if (lastMobileTimetable) {
            var $current = $(tt).find(".ff-timetable-day:visible");

            // Shall we switch to prev week?
            if ($(tt).find(".ff-timetable-day:first:visible").length > 0) {
                var startdate = $current.closest(".ff-timetable").prev().attr("data-ff-startdate");
                $current.closest(".ff-timetable-container").find(".ff-nav-switch li[data-ff-startdate='" + startdate + "'] a").click();
                return;
            }

            var $prev = $current.prev(".ff-timetable-day");
            if ($prev.length > 0) {
                $current.hide();
                $prev.show();
            }
        }
    };
    var ttMobileNext = function(tt) {
        if (lastMobileTimetable) {
            var $current = $(tt).find(".ff-timetable-day:visible");

            // Shall we switch to next week?
            if ($(tt).find(".ff-timetable-day:last:visible").length > 0) {
                var startdate = $current.closest(".ff-timetable").next().attr("data-ff-startdate");
                $current.closest(".ff-timetable-container").find(".ff-nav-switch li[data-ff-startdate='" + startdate + "'] a").click();
                return;
            }

            var $next;
            if ($current.length != 1)
                $next = $(tt).find(".ff-timetable-day:first");
            else
                $next = $current.next(".ff-timetable-day");
            if ($next.length > 0) {
                $current.hide();
                $next.show();
            }
        }
    };


    // ########################
    // ##### Query Screen #####
    // ########################
    $(".ff-nav-filter .ff-nav-group-header").click(function() {

        var group = $(this).closest(".ff-nav-group");

        if (group.hasClass("selected")) {
            group.find(".ff-nav-group-items").hide(500, function() {
                group.removeClass("selected");
            });
        } else {
            group.addClass("selected");
            group.find(".ff-nav-group-items").show(500);
        }

        return false;
    });





    $(".ff-message-notice .ff-message-close, .ff-message-notice .ff-action-messageunarchive, .ff-result .ff-message-close, .ff-result .ff-action-unarchive").click(function() {

        var animateTimeout = 500;
        var item = $(this).closest(".ff-message-notice, .ff-result");
        var page = $(this).closest(".ff-nav-content");
        var countBox = page.find("#ff-nav-count");

        var data;
        var countSelector;
        if (item.hasClass("ff-message-notice")) {
            countSelector = ".ff-message-notice";
            if ($(this).hasClass("ff-message-close"))
                data = { archive: "yes" };
            else
                data = { unarchive: "yes" };

        } else if (item.hasClass("ff-result")) {
            countSelector = ".ff-result";
            if ($(this).hasClass("ff-message-close"))
                data = { read: "true" };
            else
                data = { read: "false" };
        }


        item.hide(animateTimeout);
        countBox.html("" + (page.find(countSelector).length - 1));

        $.ajax({
            url: item.attr("data-ff-dashboard-postback"),
            type: "POST",
            data: data,
            error: function() {
                setTimeout(function() {
                    item.show();
                }, animateTimeout);

                countBox.html("" + page.find(countSelector).length);
                alert("A problem occurred submitting this request.  Please check your internet connection and try refreshing the page.");
            },
            success: function() {
                setTimeout(function() {
                    item.remove();
                    countBox.html("" + page.find(countSelector).length);
                }, animateTimeout);
            }
        });

        return false;
    });














    // #################################
    // ##### PagePlugin: BOOKMARKS #####
    // #################################

    // More
    $(".ff-bookmarks-more").click(function() {
        var bookmarks = $(this).closest(".ff-bookmarks-group").find(".ff-bookmark-hidable");

        if (bookmarks.hasClass("ff-hidden")) {
            bookmarks.removeClass("ff-hidden");
            $(this).parent().addClass("ff-expanded");
            this.innerHTML = "Collapse";
        } else {
            bookmarks.addClass("ff-hidden");
            $(this).parent().removeClass("ff-expanded");
            this.innerHTML = bookmarks.size() + " More Bookmarks";
        }

        return false;
    });


    // Personal Delete
    $(".ff-bookmark-options .ff-delete a").click(function() {
        var bookmark = $(this).closest("[data-ff-id]");
        var id = bookmark.attr("data-ff-id");

        // Hide first to prevent re-ordering errors if ajax request is delayed (and to appear more responsive!)
        bookmark.hide(500);

        $.ajax({
            url: location.href,
            type: "POST",
            data: { "delete": "" + id },
            error: function() {
                alert('A problem occurred while deleting this bookmark.  Please check your internet connection and try refreshing the page.');
                setTimeout(function() {
                    bookmark.show()
                }, 500);
            },
            success: function() {
                setTimeout(function() {
                    bookmark.remove()
                }, 500);
            }
        });

        return false;
    });


    // Personal Rename
    $(".ff-bookmark-options .ff-rename a").click(function() {
        var $content = $(this).closest(".ff-bookmark-content");
        var $text = $content.find(".ff-bookmark-text");

        var text = $text.find('a').html().replace('"', '&quot;');

        // Create input box for rename
        $content.prepend('  <form class="ff-bookmark-rename" data-ff-bookmark-href="' + $(this).attr('href') + '" data-ff-bookmark-oldtext="' + text + '"> \
			                    <input class="ff-bookmark-rename-text" type="text" value="' + text + '"/> \
			                    <input class="ff-bookmark-rename-submit" type="submit" value="Confirm change"/> \
		                    </form>');

        // Remove text box
        $text.remove();

        return false;
    });

    // Personal Rename Complete
    $(".ff-bookmark-rename-submit").live("click", function() {
        var id = $(this).closest("[data-ff-id]").attr("data-ff-id");
        var $content = $(this).closest(".ff-bookmark-content");
        var $renameform = $(this).closest(".ff-bookmark-rename");

        var href = $renameform.attr("data-ff-bookmark-href");
        var oldtext = $renameform.attr("data-ff-bookmark-oldtext");
        var newtext = $renameform.find(".ff-bookmark-rename-text").val();

        // Re-add bookmark label
        $content.prepend('  <p class="ff-bookmark-text" style="margin-top: 0"> \
                                <a href="' + href + '">' + newtext + '</a> \
                            </p>');

        // Remove the rename form
        $renameform.remove();

        // If the text has changed send it to the server
        if (oldtext != newtext) {
            $.ajax({
                url: location.href,
                type: "POST",
                data: { rename: "" + id, label: newtext },
                error: function() {
                    alert('A problem occurred while renaming this bookmark.  Please check your internet connection and try refreshing the page.');
                }
            });
        }

        return false;
    });


    // Organise
    $(".ff-bookmarks-organise").click(function() {
        $wrapper = $(this).closest(".ff-page-bookmarks");
        $(".ff-action-description", $wrapper).removeClass("ff-hidden");
        $(".ff-barrier-item", $wrapper).removeClass("ff-hidden");
        $(".ff-barrier", $wrapper).removeClass("ff-hidden");
        $(".ff-bookmarks-organise", $wrapper).addClass("ff-hidden");
        $(".ff-bookmarks-organise-done", $wrapper).removeClass("ff-hidden");

        $(".ff-bookmarks-personal").addClass("ff-bookmarks-top5 ff-draggable").sortable({
            placeholder: "ff-draggable-area",
            cancel: ".ff-barrier-item",
            forcePlaceholderSize: true,
            forceHelperSize: true,
            start: function(event, ui) {
                ui.item.addClass("ff-dragging");
            },
            stop: function(event, ui) {
                ui.item.removeClass("ff-dragging");
            },
            update: function() {
                //Update position of boundary
                var boundary = $(".ff-bookmarks-personal .ff-barrier-item");
                boundary.remove().insertAfter(".ff-bookmarks-personal li:nth-child(" + boundary.attr("data-ff-topbookmarks") + ")");

                $.ajax({
                    url: location.href,
                    type: 'POST',
                    data: $(".ff-bookmarks-personal").sortable("serialize"),
                    error: function() { alert('Error re-ordering bookmarks.  Check your internet connection and try refreshing the page.'); } // bookmarks are now out of order sync
                });
            }
        });

        return false;
    });

    // Organise Complete
    $(".ff-bookmarks-organise-done").click(function() {
        $wrapper = $(this).closest(".ff-page-bookmarks");
        $(".ff-action-description", $wrapper).addClass("ff-hidden");
        $(".ff-barrier-item", $wrapper).addClass("ff-hidden");
        $(".ff-barrier", $wrapper).addClass("ff-hidden");
        $(".ff-bookmarks-organise", $wrapper).removeClass("ff-hidden");
        $(".ff-bookmarks-organise-done", $wrapper).addClass("ff-hidden");

        $(".ff-bookmarks-personal", $wrapper).removeClass("ff-bookmarks-top5 ff-draggable").sortable("option", "disabled", true);

        return false;
    });



    // #############################
    // ##### PagePlugin: TASKS #####
    // #############################

    // Sortable Tasks
    $(".ff-tasks.ff-draggable").sortable({
        placeholder: "ff-draggable-area",
        cancel: ".ff-barrier-item",
        forcePlaceholderSize: true,
        forceHelperSize: true,
        start: function(event, ui) {
            ui.item.addClass("ff-dragging");
        },
        stop: function(event, ui) {
            ui.item.removeClass("ff-dragging");
        },
        update: function() {
            $.ajax({
                url: $(this).find(".ff-message-notice").attr("data-ff-modify-href"), // use the first message in the list
                type: "POST",
                data: "action=reorder&" + $(".ff-tasks").sortable("serialize"),
                error: function() { alert("Error re-ordering tasks.  Check your internet connection and try refreshing the page."); }
            });
        }
    });

    // Mark As Done / Undo Button
    $(".ff-message-notice .ff-action-markasdone").click(function() {
        var animateTimeout = 500;
        var noticeItem = $(this).closest(".ff-message-notice");
        var noticePage = $(this).closest(".ff-tasks-page");
        var countBox = noticePage.find("#ff-tasks-count");

        noticeItem.hide(animateTimeout);
        countBox.html("" + (noticePage.find(".ff-message-notice").length - 1));

        $.ajax({
            url: noticeItem.attr("data-ff-modify-href"),
            type: "POST",
            data: "action=done&notice_id=" + noticeItem.attr("data-ff-id") + "&ajax=on",
            error: function() {
                setTimeout(function() {
                    noticeItem.show();
                }, animateTimeout);

                countBox.html("" + noticePage.find(".ff-message-notice").length);
                alert("Error marking task as done.  Check your internet connection and try refreshing the page.");
            },
            success: function() {
                setTimeout(function() {
                    noticeItem.remove();
                    countBox.html("" + noticePage.find(".ff-message-notice").length);
                }, animateTimeout);
            }
        });

        return false;
    });
    $(".ff-message-notice .ff-action-markasdoneundo").click(function() {
        var noticeItem = $(this).closest(".ff-message-notice");
        noticeItem.hide(500);

        $.ajax({
            url: noticeItem.attr("data-ff-modify-href"),
            type: "POST",
            data: "action=doneundo&notice_id=" + noticeItem.attr("data-ff-id") + "&ajax=on",
            error: function() { alert("Error marking task as not done.  Check your internet connection and try refreshing the page."); }
        });

        return false;
    });


});
